/*---------------------------------------------------------------------------
 * Speculoos, LDAP to objet mapping.
 * Copyright (C) 2006  Norsys and OQube
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Created on Oct 20, 2005
 * --------------------------------------------------------------------------*/
package speculoos.commons.mockldap;

import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;

class SubstringFilter extends Filter {

    private String name;
    private Pattern pattern;
    SubstringFilter(String name, List strings) {
        this.name = name;
        StringBuffer regex = new StringBuffer();
        for (Iterator it=strings.iterator();it.hasNext();) {
        	String token = (String) it.next();
        	if (token.equals("*")) {
        		token= ".*";
        	}
        	regex.append(token);
        }
        	
        this.pattern = Pattern.compile(regex.toString());
        
    }

    public boolean match(TestDirContext ctx) throws NamingException {
        Attribute attr = ctx.getAttributes("",new String[]{name}).get(name);
        if(attr == null)
            return false;
        /* check object */
        for(NamingEnumeration e = attr.getAll();e.hasMore();) {
        	Object val = e.next();
        	if (val instanceof String) {
        		Matcher matcher = pattern.matcher((String) val);
        		if (matcher.matches()) {
        			return true;
        		}
			} else {
                return false;
			}
        }
        return false;
    }
    

}
